package com.kaifamiao.wendao.listener;

import com.kaifamiao.wendao.utils.MyBatisHelper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.io.Reader;

public class ContextLoaderListener implements ServletContextListener {

    @Override
    public void contextInitialized( ServletContextEvent event ) {

        ServletContext application = event.getServletContext();
        // 获取 ServletContext 初始化参数
        String resource = application.getInitParameter( "myBatisConfigLocation" );

        /* 读取配置文件并创建SqlSessionFactory实例 */
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader( resource );
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory factory = builder.build(reader);

        /* - 调用 MyBatisHelper.init 方法将 SqlSessionFactory 实例缓存起来 */
        MyBatisHelper.init( factory ); // 用类变量将 factory 保存起来

    }

    @Override
    public void contextDestroyed( ServletContextEvent event ) {
    }

}
